//表格数据
import { useState, useEffect, useMemo } from 'react';
import ProTable from '@/components/ProTable';
import { recordColumns } from '../config';
import { getColumnsData } from '../config/columns';
import { queryRecordList, getRecordPrintDetail } from '../service';
import PrintModal from '../component/PrintModal';

const RecordList = (props) => {

	const { formData, realColumns, headerHeight, changeShowDetail } = props;

	const [visible, setVisible] = useState(null);

	const [data, setData] = useState([]);

	const [printData, setPrintData] = useState([]);

	useEffect(() => {
		getTableList();
	}, [formData]);

	//获取数据
	const getTableList = async () => {
		START_LOADING();
    const params = {
      supplierAreaList: formData.supplierAreaList?.length > 0 ? formData.supplierAreaList : undefined,
      supplierIdList: formData.supplierIdList?.length > 0 ? formData.supplierIdList : undefined
    }
		if(formData.time) {
			params.startTime = formData.time[0].format('YYYY-MM-DD 00:00:00');
			params.endTime = formData.time[1].format('YYYY-MM-DD 23:59:59');
		}
		const { success, data } = await queryRecordList(params);
		if (success) {
			setData(data);
		}
		END_LOADING();
	}

	//获取打印记录详情
	const getPrintDetail = async (printId) => {
		START_LOADING();
		const { success, data } = await getRecordPrintDetail({
			printId
		})
		END_LOADING();
		if (success) {
			return [ data ];
		}
		return [];
	}

	//获取详情
	const handleViewDetail = async (val) => {
		const arr = await getPrintDetail(val);
		if(arr.length > 0) {
			changeShowDetail(arr);
		}
	}

	//点击打印历史记录
	const handlePrint = async (val) => {
		const arr = await getPrintDetail(val);
		setPrintData(arr);
		setVisible('printModal');
	}

	//处理打印数据
	const getPrintData = (printName) => {
		const list = [];
		printData.forEach((item) => {
			list.push({
				supplierName: item.supplierName,
				supplierArea: item.supplierArea,
				accountNo: item.accountNo,
				supplierSkuQuantity: item.supplierSkuQuantity,
				supplierSkuTotalPrice: item.supplierSkuTotalPrice,
				goodsList: item.pickingGoodsSummarySpuVOList,
				columns: getColumnsData({
					columns: realColumns,
				}),
				index: printName,
			});
		});
		return list;
	}

	//选择打印机
	const PrintModalProps = {
		getPrintData,
		handleCancel() {
			setVisible(null);
		},
	};

	//渲染展示的列
	const columns = useMemo(() => {
		return getColumnsData({
			columns: recordColumns,
			//查看详情
			handleViewDetail,
			//打印备货汇总
			handlePrint,
		})
	}, [])

	//表格组件参数
	const ProTableProps = {
		data,
		columns,
		style: {
			height: `calc(100vh - ${headerHeight}px)`
		},
	};

	return (
		<div className='views-virtual-table-wrap' style={{ marginTop: '16px', background: '#fff', padding: '16px' }}>
			<ProTable {...ProTableProps} />
			{visible == 'printModal' && <PrintModal {...PrintModalProps} />}
		</div>
	)
}

export default RecordList;